package com.ziyueyuwen.xiniao.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.dingtalk.api.response.OapiAuthScopesResponse;
import com.dingtalk.api.response.OapiDepartmentListResponse;
import com.dingtalk.api.response.OapiUserListResponse;
import com.ziyueyuwen.xiniao.bean.ZyDingTalkUser;
import com.ziyueyuwen.xiniao.bean.ZyUser;
import com.ziyueyuwen.xiniao.bean.ZyUserWx;
import com.ziyueyuwen.xiniao.bean.vo.ZyUserVO;
import com.ziyueyuwen.xiniao.bean.wx.TbWxUserInfo;
import com.ziyueyuwen.xiniao.dao.TbWxUserInfoMapper;
import com.ziyueyuwen.xiniao.dao.ZyDingTalkUserMapper;
import com.ziyueyuwen.xiniao.dao.ZyUserMapper;
import com.ziyueyuwen.xiniao.dao.ZyUserWxMapper;
import com.ziyueyuwen.xiniao.service.ThirdPartService;
import com.ziyueyuwen.xiniao.service.UserService;
import com.ziyueyuwen.xiniao.thirdpart.util.DingTalkUtil;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author wancheng  on 2018/12/19.
 */
@Service
public class ThirdPartServiceImpl implements ThirdPartService {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    ZyDingTalkUserMapper zyDingTalkUserMapper;
    @Autowired
    TbWxUserInfoMapper tbWxUserInfoMapper;
    @Autowired
    ZyUserWxMapper zyUserWxMapper;
    @Autowired
    UserService userService;
    @Autowired
    ThirdPartService thirdPartService;
    @Autowired
    ZyUserMapper zyUserMapper;

    @Override
    public void loadDingTalkUser() {
        //获取此token授权范围
        OapiAuthScopesResponse authScopesResponse = DingTalkUtil.getAuthScopes();
        //获取授权部门列表
        List<Long> deptIds = authScopesResponse.getAuthOrgScopes().getAuthedDept();
        logger.info("获取钉钉权限部门列表={}" + JSONArray.toJSONString(deptIds));
        //同步钉钉的
        List<String> dingUserIds = new ArrayList<>();
        for (Long deptId : deptIds) {
            //获取当前部门信息
            logger.info("获取当前部门信息  deptId = {}", deptId);
            //获取当前部门下员工信息
            List<String> deptUserList = insertDeptUserList(deptId);
            dingUserIds.addAll(deptUserList);
            //获取下属子部门列表
            OapiDepartmentListResponse deptChild = DingTalkUtil.getDepartmentChildList(deptId.toString());
            for (OapiDepartmentListResponse.Department child : deptChild.getDepartment()) {
                //获取部门下员工信息
                List<String> childUserList = insertDeptUserList(child.getId());
                dingUserIds.addAll(childUserList);
            }
        }
        this.deleteSysUser(dingUserIds);

    }

    /**
     * 同步钉钉,逻辑删除数据库中离职的员工
     * @param dingUsers
     */
    private void deleteSysUser(List<String> dingUsers){
        if (CollectionUtils.isEmpty(dingUsers)){
            return;
        }
        List<ZyUserVO> users = zyUserMapper.getUserByUserAccountOrUserName(null,true);
        List<String> originalUserAccount = users.stream().map(ZyUserVO::getUserAccount).collect(Collectors.toList());
        List<String> deleteUserAccount = originalUserAccount.stream().filter(a->!dingUsers.contains(a)).collect(Collectors.toList());
        if (!CollectionUtils.isEmpty(deleteUserAccount)){
            deleteUserAccount.forEach(
                    zyUserMapper::deleteUser
            );
        }
    }
    @Override
    public String getDingTalkId(String userAccount) {
        ZyDingTalkUser user = new ZyDingTalkUser();
        user.setUserAccount(userAccount);
        user.setIfDelete(false);
        ZyDingTalkUser zyDingTalkUser = zyDingTalkUserMapper.selectOne(user);
        if (zyDingTalkUser != null){
            return  zyDingTalkUser.getDingTalkId();
        }
        return null;
    }

    @Override
    public String getOpenId(String userAccount) {
        TbWxUserInfo tbWxUserInfo = tbWxUserInfoMapper.getByAccount(userAccount);
        if (tbWxUserInfo != null){
            return tbWxUserInfo.getOpenid();
        }
        return null;
    }

    @Override
    public void bindWx(String userAccount, String wxUserId) throws Exception {
        ZyUserVO user = userService.getUserMessage(userAccount);
        if (user == null){
            throw new Exception("用户不存在");
        }
        TbWxUserInfo wxUserInfo = getWxInfoByWxUserId(wxUserId);
        if (wxUserInfo == null){
            throw new Exception("微信信息不存在");
        }
        TbWxUserInfo tbWxUserInfo = thirdPartService.getWxMessage(userAccount);
        if (tbWxUserInfo != null){
            throw new Exception("手机号已绑定微信");
        }
        ZyUser zyUser =  getUserMessage(wxUserId);
        if (zyUser != null){
            throw new Exception("该微信已绑定");
        }
        ZyUserWx zyUserWx = new ZyUserWx();
        zyUserWx.setUserAccount(userAccount);
        zyUserWx.setWxUserId(wxUserId);
        zyUserWxMapper.insertSelective(zyUserWx);
    }

    @Override
    public void removeWxBind(String userAccount) throws Exception {
        ZyUser student = userService.getByAccount(userAccount);
        if (student == null){
            throw new Exception("用户不存在");
        }
        ZyUserWx userWx = new ZyUserWx();
        userWx.setUserAccount(userAccount);
        zyUserWxMapper.delete(userWx);
    }

    @Override
    public void removeWxBindByWxUserId(String wxUserId) throws Exception {
        ZyUserWx userWx = new ZyUserWx();
        userWx.setWxUserId(wxUserId);
        zyUserWxMapper.delete(userWx);
    }

    @Override
    public TbWxUserInfo getWxMessage(String userAccount) {
        TbWxUserInfo tbWxUserInfo = tbWxUserInfoMapper.getByAccount(userAccount);
        return tbWxUserInfo;
    }

    @Override
    public ZyUser getUserMessage(String wxUserId) {
        return userService.getByWxUserId(wxUserId);
    }

    @Override
    public TbWxUserInfo getWxInfoByWxUserId(String wxUerId) {
        return tbWxUserInfoMapper.getByWxUserId(wxUerId);
    }

    private List<String> insertDeptUserList(Long deptId) {
        List<String> userIds = new ArrayList<>();
        OapiUserListResponse userResponse = DingTalkUtil.getUserList(deptId);
        List<OapiUserListResponse.Userlist> userList = userResponse.getUserlist();
        userList.forEach(
                user -> {
                    userIds.add(user.getMobile());
                    ZyDingTalkUser currentUser = getUser(user);
                    ZyDingTalkUser zyDingTalkUser = zyDingTalkUserMapper.getByDingTalkId(currentUser.getDingTalkId());
                    if (zyDingTalkUser == null) {
                        insertDingUser(currentUser);
                    } else {
                        currentUser.setId(zyDingTalkUser.getId());
                        updateDingUser(currentUser);
                    }
                }
        );
        logger.info("更新用户信息:" + userResponse.getBody());
        return userIds;
    }

    public void insertDingUser(ZyDingTalkUser currentUser ){
        zyDingTalkUserMapper.insertSelective(currentUser);
        ZyUser user = new ZyUser();
        user.setCreateTime(new Date());
        user.setIfDelete(false);
        user.setUserAccount(currentUser.getUserAccount());
        user.setUserName(currentUser.getNickName());
        user.setIfSysUser(true);
        try {
            userService.saveTeacher(user);
        }catch (Exception e){
            e.printStackTrace();
        }
    }
    public void updateDingUser(ZyDingTalkUser currentUser ){
        zyDingTalkUserMapper.updateByPrimaryKeySelective(currentUser);
        ZyUser user = userService.getByAccount(currentUser.getUserAccount());
        try {
            user.setIfSysUser(true);
            user.setUserName(currentUser.getNickName());
            user.setEmail(currentUser.getEmail());
            zyUserMapper.updateByPrimaryKeySelective(user);
        }catch (Exception e){
            e.printStackTrace();
        }
    }
    public ZyDingTalkUser getUser(OapiUserListResponse.Userlist duser) {
        ZyDingTalkUser user = new ZyDingTalkUser();
        user.setDingTalkId(duser.getUserid());
        user.setRemark(duser.getRemark());
        user.setUserAccount(duser.getMobile());
        user.setIfDelete(false);
        user.setActive(duser.getActive());
        user.setDingId(duser.getDingId());
        user.setAvatar(duser.getAvatar());
        user.setEmail(duser.getEmail());
        user.setHiredDate(duser.getHiredDate());
        user.setIsAdmin(duser.getIsAdmin());
        user.setIsBoss(duser.getIsBoss());
        user.setIsHide(duser.getIsHide());
        user.setIsLeader(duser.getIsLeader());
        if (!StringUtils.isBlank(duser.getJobnumber())) {
            user.setJobnumber(Long.valueOf(duser.getJobnumber()));
        }
        user.setMobile(duser.getMobile());
        user.setNickName(duser.getName());
        user.setUnionId(duser.getUnionid());
        user.setDingTalkOrder(duser.getOrder());
        user.setOrgEmail(duser.getOrgEmail());
        user.setWorkPlace(duser.getWorkPlace());
        return user;
    }
}
